<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户登录 - 区块链物流系统</title>
    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Font Awesome -->
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <!-- 配置Tailwind CSS自定义颜色和字体 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3B82F6', // 蓝色主色调
                        secondary: '#10B981', // 绿色辅助色
                        accent: '#6366F1', // 紫色强调色
                        dark: '#1E293B', // 深色
                        light: '#F8FAFC' // 浅色
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style>
        /* 全局样式 */
        body {
            background-color: #f8fafc;
            background-image: radial-gradient(#e2e8f0 1px, transparent 1px), radial-gradient(#e2e8f0 1px, transparent 1px);
            background-size: 50px 50px;
            background-position: 0 0, 25px 25px;
        }
        /* 动画效果 */
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        .animate-fadeIn {
            animation: fadeIn 0.6s ease-out forwards;
        }
        .btn-hover {
            transition: all 0.3s ease-in-out;
        }
        .btn-hover:hover {
            box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
            transform: translateY(-2px);
        }
    </style>
</head>
<body class="font-inter min-h-screen flex items-center justify-center p-4">
    <!-- 主容器 -->
    <div class="w-full max-w-md animate-fadeIn">
        <!-- 标题区域 -->
        <div class="text-center mb-8">
            <h1 class="text-[clamp(1.5rem,3vw,2rem)] font-bold text-dark mb-4">
                <i class="fa fa-user-circle text-3xl mr-3 text-primary"></i>用户登录
            </h1>
            <p class="text-gray-600">区块链物流系统 - 用户认证</p>
        </div>

        <!-- 卡片容器 -->
        <div class="bg-white rounded-xl shadow-lg p-6">
            <!-- 标签切换 -->
            <div class="flex border-b mb-4">
                <button id="login-tab" class="flex-1 py-2 text-center font-medium text-primary border-b-2 border-primary">
                    <i class="fa fa-sign-in mr-2"></i>登录
                </button>
                <button id="register-tab" class="flex-1 py-2 text-center font-medium text-gray-500 hover:text-gray-700">
                    <i class="fa fa-user-plus mr-2"></i>注册
                </button>
            </div>

            <!-- 登录表单 -->
            <form id="login-form" class="space-y-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">用户ID</label>
                    <input type="number" id="login-id" required
                        class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary"
                        placeholder="请输入用户ID">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">密码</label>
                    <input type="password" id="login-password" required
                        class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary"
                        placeholder="请输入密码">
                </div>
                <button type="submit" class="w-full bg-primary text-white py-2 rounded-lg font-medium btn-hover">
                    <i class="fa fa-sign-in mr-2"></i>登录
                </button>
            </form>

            <!-- 注册表单 -->
            <form id="register-form" class="space-y-4 hidden">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">用户名</label>
                    <input type="text" id="register-username" required
                        class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary"
                        placeholder="请输入用户名">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">密码</label>
                    <input type="password" id="register-password" required
                        class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary"
                        placeholder="请输入密码">
                </div>
                <button type="submit" class="w-full bg-secondary text-white py-2 rounded-lg font-medium btn-hover">
                    <i class="fa fa-user-plus mr-2"></i>注册
                </button>
            </form>

            <!-- 结果提示 -->
            <div id="result-message" class="hidden mt-4 p-3 rounded text-center"></div>
        </div>

        <!-- 返回主页面链接 -->
        <div class="mt-6 text-center">
            <a href="index.html" class="text-primary hover:text-primary/80 font-medium">
                <i class="fa fa-arrow-left mr-2"></i>返回角色选择
            </a>
        </div>
    </div>

    <!-- JavaScript -->
    <script>
        // 全局变量
        const API_BASE = 'http://localhost:8080';

        // DOM元素
        const loginTab = document.getElementById('login-tab');
        const registerTab = document.getElementById('register-tab');
        const loginForm = document.getElementById('login-form');
        const registerForm = document.getElementById('register-form');
        const resultMessage = document.getElementById('result-message');

        // 初始化
        function init() {
            // 添加事件监听器
            loginTab.addEventListener('click', () => switchForm('login'));
            registerTab.addEventListener('click', () => switchForm('register'));
            loginForm.addEventListener('submit', handleLogin);
            registerForm.addEventListener('submit', handleRegister);
        }

        // 切换表单
        function switchForm(type) {
            if (type === 'login') {
                // 激活登录表单
                loginTab.classList.add('text-primary', 'border-b-2', 'border-primary');
                loginTab.classList.remove('text-gray-500');
                registerTab.classList.add('text-gray-500');
                registerTab.classList.remove('text-primary', 'border-b-2', 'border-primary');
                loginForm.classList.remove('hidden');
                registerForm.classList.add('hidden');
            } else {
                // 激活注册表单
                registerTab.classList.add('text-primary', 'border-b-2', 'border-primary');
                registerTab.classList.remove('text-gray-500');
                loginTab.classList.add('text-gray-500');
                loginTab.classList.remove('text-primary', 'border-b-2', 'border-primary');
                registerForm.classList.remove('hidden');
                loginForm.classList.add('hidden');
            }
            hideMessage();
        }

        // 显示消息
        function showMessage(message, isSuccess = true) {
            resultMessage.textContent = message;
            resultMessage.className = 'mt-4 p-3 rounded text-center';
            resultMessage.classList.add(isSuccess ? 'bg-green-50', 'text-green-700' : 'bg-red-50', 'text-red-700');
            resultMessage.classList.remove('hidden');
        }

        // 隐藏消息
        function hideMessage() {
            resultMessage.classList.add('hidden');
        }

        // 跳转到用户主页
        function redirectToDashboard(id) {
            window.location.href = `user.html?id=${id}&role=user`;
        }

        // 处理注册表单提交
        async function handleRegister(e) {
            e.preventDefault();
            const username = document.getElementById('register-username').value;
            const passwd = document.getElementById('register-password').value;

            if (!username || !passwd) {
                showMessage('请填写完整信息', false);
                return;
            }

            try {
                const response = await fetch(`${API_BASE}/user/add`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ username, passwd })
                });
                
                const data = await response.json();

                if (data.code === '0') {
                    showMessage(`注册成功！欢迎 ${username}`, true);
                    registerForm.reset();
                    // 注册成功后切换到登录表单
                    setTimeout(() => switchForm('login'), 2000);
                } else {
                    showMessage(`注册失败: ${data.message || '请重试'}`, false);
                }
            } catch (error) {
                console.error('注册错误:', error);
                if (error.message.includes('Failed to fetch')) {
                    showMessage('无法连接到服务器，请检查后端服务是否启动', false);
                } else {
                    showMessage('注册失败，请重试', false);
                }
            }
        }

        // 处理登录表单提交
        async function handleLogin(e) {
            e.preventDefault();
            const id = parseInt(document.getElementById('login-id').value);
            const passwd = document.getElementById('login-password').value;

            if (!id || !passwd) {
                showMessage('请输入ID和密码', false);
                return;
            }

            try {
                const response = await fetch(`${API_BASE}/user/check`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ id, passwd })
                });
                
                const data = await response.json();

                if (data.code === '0') {
                    showMessage('登录成功！正在跳转...', true);
                    setTimeout(() => {
                        redirectToDashboard(id);
                    }, 1000);
                } else {
                    showMessage(`登录失败: ${data.message || 'ID或密码错误'}`, false);
                }
            } catch (error) {
                console.error('登录错误:', error);
                if (error.message.includes('Failed to fetch')) {
                    showMessage('无法连接到服务器，请检查后端服务是否启动', false);
                } else {
                    showMessage('登录失败，请重试', false);
                }
            }
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', init);
    </script>
</body>
</html>